package org.dendy.app.ssh;

import java.io.ByteArrayInputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class Connection {

	protected JSch jsch;

	protected String user;

	protected String pass;

	protected String host;

	protected Session session;

	protected Properties properties;

	protected ChannelExec channelExec;

	protected String command = null;

	void connectionServer() throws JSchException {
		jsch = new JSch();
		user = "root";
		pass = "andika";
		host = "192.168.0.101";

		/*angka 22 ada port,masukan port yang anda miliki*/
		session = jsch.getSession(user, host, 222);
		session.setPassword(pass);
		properties = new Properties();
		properties.put("StrictHostKeyChecking", "no");
		session.setConfig(properties);
		session.connect();
		System.out.println("connect ke server");
		command = "init 0";

		channelExec = (ChannelExec) session.openChannel("exec");
		channelExec.setCommand(command);
		channelExec.setInputStream(System.in);
		((ChannelExec) channelExec).setErrStream(System.err);
	}

	/**
	 * method untuk button reboot
	 * 
	 * @throws JSchException
	 */
	void actionReboot() throws JSchException {
		connectionServer();
		Channel channel = session.openChannel("shell");
		channel.setInputStream(System.in);
		ByteArrayInputStream bi = new ByteArrayInputStream(
				"init 6\r".getBytes());
		channel.setInputStream(bi);
		channel.connect(30000);
	}

	/**
	 * Method untuk button off
	 * 
	 * @throws JSchException
	 */
	void actionOff() throws JSchException {
		connectionServer();
		Channel channel = session.openChannel("shell");
		channel.setInputStream(System.in);
		ByteArrayInputStream bi = new ByteArrayInputStream(
				"init 0\r".getBytes());
		channel.setInputStream(bi);
		channel.connect(30000);
	}

}
